var Templater = {
	state: {
		_workspace: [];
		workspace: {
			add: function(widget) {
				this._workspace.push(widget);
			},
			remove: function(widget) {
				this._workspace.slice(this._workspace.indexOf(widget), 1);
			},
			all: function() {
				return this._workspace;
			},
			get: function(widget) {
				return this._workspace(this._workspace.indexOf(widget));
			}
		}
	},
	render: {
		_contents: {
			course: Handlebars.compile("<h1>{{attr/title}}</h1><h3>{{attr/code}}</h3>"),
			person: Handlebars.compile("<h1>{{attr/name}}</h1>"),
			schedule: Handlebars.compile("<h1>{{attr/location}}</h1><h2>{{attr/campus}}</h2><p>{{attr/date_start}} - {{attr/date_end}}</p>"),
			value: Handlebars.compile("<h3>{{value}}</h3>")
		},
		_select: function() {
			return $("<select/>")
				.append($("<option/>", { value: "or", text: "or" }))
				.append($("<option/>", { value: "and", text: "and" }))
				.append($("<option/>", { value: "not", text: "not" }))
				.change(function() {
					var _event = $.Event("operatorchanged");
					_event.op = $(this).val();
					
					$("body").trigger(_event);
				});
		},
		widget: function(type, context, parent, inject) {
			var x_button = $("<a/>")
				.append($("<span/>")
					.addClass("ui-icon")
					.addClass("ui-icon-circle-close"))
				.hide();
			
			var resolvedType = isValue(context) ? "value" : type,
				contents = Templater.render._contents[resolvedType](context),
				select = Templater.render._select();
			
			var complete = $("<div/>")
				.addClass("widget")
				.append(contents)
				.append(inject)
				.append(select)
				.append(x_button);
			
			x_button.click(function() {
				complete.fadeOut(500, function() {
					complete.remove();
				});
			});
			
			select.wrap($("<p>").addClass("select-box"));
			
			if (typeof parent != "undefined") {
				complete.appendTo(parent);
			}
			
			return complete;
		}
	}
};
